import router from './router'
import store from './store'
import {
  Message
} from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import {
  getToken
} from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({
  showSpinner: false
}) // NProgress Configuration

const whiteList = ['/login', '/auth-redirect', '/404'] // no redirect whitelist

router.beforeEach(async (to, from, next) => {
  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in
  const hasToken = getToken() //cookies：浏览器是否有token
  const hasName = sessionStorage.getItem('name') //sessionStorage里面是否有用户姓名（浏览器关闭，sessionStorage清除）
  const hasUserInfo = store.getters.name //vuex 是否有用户信息（F5刷新，vuex数据丢失）
  const toPath = to.path
  const fullPath = to.fullPath

  if (hasToken && hasName) { //如果Cookies有token && sessionStorage有用户姓名
    if (hasUserInfo) { //vuex有用户信息
      if (to.path === '/login') {  //在登陆页面可以直接跳转dashboard
        next({
          path: '/'
        })
        NProgress.done()
      } else {            //其他页面正常跳转
        next()
        NProgress.done()
      }
    } else {    //vuex没有用户信息，需要调用getUserInfo，拿到用户及菜单信息
      if (to.path === `/login`) {        //在登陆页面，保持当前登陆页面，无需调用接口
        next()
        NProgress.done()
      } else {  //其他情况，需要调用getUserInfo接口
        const {
          roles,
          menus
        } = await store.dispatch('user/getInfo') // 调取后端接口，获取角色信息 以及 菜单信息（路由）
        menus.push({
          path: '*',
          redirect: '/404',
          hidden: true
        }) // 在动态路由的最后，必须添加一个404页面
        // generate accessible routes map based on roles
        const accessRoutes = await store.dispatch('permission/generateRoutes', {
          roles,
          menus
        }) // 基于角色，获得相关路由信息

        router.addRoutes(accessRoutes) // 动态添加路由

        // hack method to ensure that addRoutes is complete
        // set the replace: true, so the navigation will not leave a history record
        next({
          ...to,
          replace: true
        })
        NProgress.done()
      }
    }
  } else {
    /* has no token*/
    if (whiteList.indexOf(to.path) !== -1) {
      next()  //如果在白名单，直接进入
      NProgress.done()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
